<?php


/**
 * User: wu
 * Date:2019/12/12
 * time:16:35
 * 
 */
namespace app;
require_once __DIR__.'/common/TableTool.php';
require_once __DIR__.'/common/Validate.php';
require_once __DIR__.'/common/Common.php';
require_once __DIR__.'/common/Log.php';
require_once __DIR__.'/common/RpcClient.php';

use \GatewayWorker\Lib\Gateway; //？
use app\common\TableTool;
use app\common\Validate;
use app\common\Common;
use app\common\Log;
use RpcClient;

//基类文件
class BaseController
{
    
    /**
     * 路由入口
     * @param  [type] $client_id [description]
     * @param  [type] $message   [description]
     * @return [type]            [description]
     *
     * 保存公用类对象
     */
    protected $table = null; //数据库
    protected $validate = null; //验证
    protected $common = null;  //常用函数对象
    protected $log = null;


    public $db_sys = null;
    
    protected $api = '';
    /**
     * 过滤掉，无需处理的消息接口
     */
    public $api_ignore_method_list = array();
    protected $admin_id = null;
    protected $login_type = null;

        /**
     * [__construct description]
     * 构造函数
     */
    public function __construct()
    {
        $this->table = new TableTool(); 
        $this->validate = new Validate();
        $this->common = new Common(); 
        $this->log = new Log();

        //rpc 初始
        $this->rpc_config();

        $this->admin_id = isset($_SESSION['admin_id'])?$_SESSION['admin_id']:'';
        $this->login_type = isset($_SESSION['login_type'])?$_SESSION['login_type']:'';
        $this->_initialize();
    }




    public function rpc_instance($name='')
    {
        return RpcClient::instance($name);
    }

    public function rpc_config()
    {
        $address_array = array(
              'tcp://192.168.101.201:2015',
              'tcp://192.168.101.201:2015'
              );
        RpcClient::config($address_array);
    }

    public function log($data='',$level='normal')
    {
        $this->log->log($data,$level);
    }



    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    { 

    }

    /**
     * 向客户端发送信息
     * 
     * @param unknown $res
     * 
     * @return \think\response\Json
     */
    // public function outMessage($api= '',$code = 0,$message = "request success",$data = array(),$status = 'success',$count = 0)
    public function outMessage($code = 0,$message = "request success",$data = array(),$status = 'ok',$count = 0)
    {   
        $codeMap = array('0'=>'success','111'=>'未知错误');
        if ($code!=0) {
            // $status = 'error';
            if (!$message) {
                $message = $codeMap[$code];
            }
        }
        
        $data = [
            'api' => $this->api,
            'code' => $code,
            'message' => $message,
            'status' => $status,
            'type' => $_SESSION['returnType'],
            'count' => $count,
            'data' => $data
        ];
        if($data){
            $this->log('向用户发送数据');
            $this->log($data);

            return Gateway::sendToCurrentClient(json_encode($data)."\r\n");
        }else{
            abort(404);
        }
    }



    /**
     * 路由入口
     */
    public function entrance($message)
    {   

        if(in_array($message,array('{"type":"pong"}','{"type":"ping"}'))){

            return;
        }
        if(is_null($message)){
            return;
        }
        if(is_null(json_decode($message))){
            return $this->outMessage(9999,"API messages are not legitimate JSON formats!".$message,[]);
        }
        $msg = json_decode($message,true);
        if(!isset($msg['api'])){
            return $this->outMessage(9998,'unknow error!',[]);
        }


        //客户端连接上后记录类型
        //来自pc的消息     ? 端口
        if($_SESSION['app_type'] == 'pda' || $_SESSION['app_type'] == 'pc'){

            $this->api = $msg['api'];

            $arr_api = explode('_',$msg['api']);

            $module = $arr_api[1];
            $class_name = ucfirst($arr_api[2]); //controller
            $action_name = $arr_api[3];
            
            // 文件必须存在 否则会报错
            var_dump('module_name:'.$module);
            var_dump('class_name:'.$class_name);
            var_dump('action_name:'.$action_name);

            

            // 判断文件路径是否存在
            $dir = PATH.'controller/'.$module;
            var_dump('查找目录：'.$dir);
            if(!is_dir($dir)){
                var_dump('模块路径不存在');
                return $this->outMessage(9996,'method not find!');
            }

            // 判断文件是否存在
            $php_field = PATH.'controller/'.$module.'/'.$class_name.'.php';
            var_dump('查找文件：'.$php_field);
            if(!file_exists($php_field)){
                var_dump('类文件不存在');
                return $this->outMessage(9996,'method not find!');
            }

            var_dump('include 文件');
            include_once PATH.'controller/'.$module.'/'.$class_name.'.php';
            try {
                // $obj 控制器类
                $controller = new $class_name();
                var_dump('检查方法是否存在');
                if(method_exists($controller,$action_name)){ 
                    // 这边做身份验证 
                    // $auth = new Auth();
                    // $auth->check($msg['api']);


                    //未身份验证，当前接口不是做身份验证，则拒绝调用
                    if(!isset($_SESSION['user_id'])){
                        return $this->outMessage(9991,'device authentication faile, call auth api first',[],'error');
                    }else{



                        //初始化返回消息，以后可以放到公共或基类中
                        $controller->init($msg);
                        $controller->api = $msg['api'];
                        //根据api 名称动态路由调用函数
                        $log[] = '调用了接口';
                        $log[] = $msg['api'];
                        $this->log($log,'debug');


                        $controller->$action_name($msg); 
                    }

                }else{
                     //接口不存在
                     var_dump('方法不存在');
                     return $this->outMessage(9996,'method not find!');
                }
            } catch (Exception $e) {
                echo $e->getMessage();
                return $this->outMessage(9996,'method not find!',[],'error');
            }    
        }
        return;
    }



}





